package com.osgix.common.utils;

import java.util.HashMap;
import java.util.Map;

import org.extremecomponents.table.limit.Filter;
import org.extremecomponents.table.limit.Limit;
import org.extremecomponents.table.limit.Sort;

import com.osgix.common.orm.ibatis.PageRequest;

public class ExtremeTablePageRequestFactory {

	public ExtremeTablePageRequestFactory() {
	}

	public static PageRequest createFromLimit(Limit limit, String defaultSortColumns) {
		PageRequest result = new PageRequest();
		result.setPageNumber(limit.getPage());
		result.setPageSize(limit.getCurrentRowsDisplayed());
		result.setSortColumns(getSortingColumns(limit, defaultSortColumns));
		result.setFilters(getFilters(limit));
		return result;
	}

	public static PageRequest createFromLimit(Limit limit) {
		return createFromLimit(limit, null);
	}

	private static Map getFilters(Limit limit) {
		Filter filters[] = limit.getFilterSet().getFilters();
		Map result = new HashMap();
		for (int i = 0; i < filters.length; i++) {
			Filter filter = filters[i];
			result.put(filter.getAlias(), filter.getValue());
		}

		return result;
	}

	public static String getSortingColumns(Limit limit, String defaultSortColumns) {
		Sort sort = limit.getSort();
		if (sort.getProperty() == null) {
			return defaultSortColumns;
		} else {
			String sortOrder = sort.getSortOrder() != null ? (new StringBuilder()).append(" ")
					.append(sort.getSortOrder()).toString() : "";
			String column = sort.isAliased() ? sort.getAlias() : sort.getProperty();
			String sortColumns = (new StringBuilder()).append(column).append(sortOrder).toString();
			return sortColumns;
		}
	}
}